//# 敌人AI脚本

using UnityEngine;

public class EnemyAI : BaseCharacter
{
    public float detectionRange = 5f;
    public float attackRange = 1f;
    private Transform player;
    private float nextAttackTime = 0f;
    public float attackCooldown = 2f;

    protected override void Start()
    {
        base.Start();
        player = GameObject.FindGameObjectWithTag("Player").transform;
    }

    void Update()
    {
        if (player == null) return;

        float distanceToPlayer = Vector2.Distance(transform.position, player.position);

        // 在检测范围内但不在攻击范围内时移动
        if (distanceToPlayer < detectionRange && distanceToPlayer > attackRange)
        {
            Vector2 direction = (player.position - transform.position).normalized;
            rb.velocity = new Vector2(direction.x * moveSpeed, rb.velocity.y);

            // 转向
            if (direction.x > 0 && !isFacingRight)
                Flip();
            else if (direction.x < 0 && isFacingRight)
                Flip();
        }
        // 在攻击范围内时攻击
        else if (distanceToPlayer <= attackRange && Time.time >= nextAttackTime)
        {
            Attack();
            nextAttackTime = Time.time + attackCooldown;
        }
    }

    void Attack()
    {
        animator?.SetTrigger("Attack");
        player.GetComponent<BaseCharacter>()?.TakeDamage(10f);
    }
}